package com.nb.controller;

import com.mybatisflex.core.paginate.Page;
import com.nb.dto.LogStatisticsDTO;
import com.nb.dto.SysLogQueryDTO;
import com.nb.entity.SysLog;
import com.nb.result.CsvExportUtil;
import com.nb.service.SysLogService;
import com.nb.result.Result;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.constraints.Min;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.List;

@RestController
@RequestMapping("/log")
public class SysLogController {

    private static final Logger logger = LoggerFactory.getLogger(SysLogController.class);
    @Autowired
    private SysLogService sysLogService;

    /**
     * 多条件分页查询操作日志
     */
    @GetMapping("/list")
    public Result getLogList(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) Long userId,
            @RequestParam(required = false) String action,
            @RequestParam(required = false) String targetType,
            @RequestParam(required = false) Long targetId,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime startTime,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endTime) {

        // 构建查询参数
        SysLogQueryDTO queryDTO = new SysLogQueryDTO();
        queryDTO.setPageNum(pageNum);
        queryDTO.setPageSize(pageSize);
        queryDTO.setUserId(userId);
        queryDTO.setAction(action);
        queryDTO.setTargetType(targetType);
        queryDTO.setTargetId(targetId);
        queryDTO.setStartTime(startTime);
        queryDTO.setEndTime(endTime);

        // 调用服务查询
        Page<SysLog> page = sysLogService.getSysLogPage(queryDTO);

        return Result.success(page);
    }
    @GetMapping("/detail/{id}")
    public Result getLogDetail(@PathVariable @Min(value = 1, message = "日志ID必须大于等于1") Long id) {
        logger.info("Received log detail request, logId: {}", id);

        // 查询日志详情
        SysLog sysLog = sysLogService.getLogById(id);

        if (sysLog == null) {
            logger.warn("Log not found, logId: {}", id);
            return Result.error("日志不存在或已被删除");
        }

        logger.info("Log detail query successful, logId: {}", id);
        return Result.success(sysLog);
    }
    @GetMapping("/statistics")
    public Result getLogStatistics(
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime startTime,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endTime) {

        LogStatisticsDTO statisticsDTO = new LogStatisticsDTO();

        // 按日期统计
        List<LogStatisticsDTO.DateCountVO> dailyStats = sysLogService.countByDate(startTime, endTime);
        statisticsDTO.setDailyStatistics(dailyStats);

        // 按操作类型统计
        List<LogStatisticsDTO.TypeCountVO> typeStats = sysLogService.countByAction(startTime, endTime);
        statisticsDTO.setTypeStatistics(typeStats);

        // 按用户统计
        List<LogStatisticsDTO.UserCountVO> userStats = sysLogService.countByUser(startTime, endTime);
        statisticsDTO.setUserStatistics(userStats);

        return Result.success(statisticsDTO);
    }

    @GetMapping("/export")
    public void exportLogs(
            HttpServletResponse response,
            @RequestParam(required = false) Long userId,
            @RequestParam(required = false) String action,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime startTime,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endTime
    ) throws IOException {

        // 1. 查询导出数据
        List<SysLog> exportData = sysLogService.queryLogsForCsvExport(userId, action, startTime, endTime);

        // 2. 设置响应头
        response.setContentType("text/csv");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("操作日志_" + System.currentTimeMillis(), StandardCharsets.UTF_8.name())
                + ".csv";
        response.setHeader("Content-disposition", "attachment;filename*=UTF-8''" + fileName);

        // 3. 定义CSV表头（与SysLog字段对应）
        String[] headers = {
                "日志ID", "操作用户ID", "操作类型", "操作对象类型",
                "操作对象ID", "变更详情", "操作IP", "操作时间"
        };

        // 4. 写入CSV文件
        CsvExportUtil.export(response.getOutputStream(), headers, exportData);
    }
}